package com.ylr.config.framework.resolver;

import com.ylr.config.common.dto.mapping.SimpleMappingDto;
import com.ylr.base.common.exception.YlrException;
import com.ylr.base.common.tool.Result;
import com.ylr.config.framework.feign.client.YcMappingClient;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-05-03 18:06:49
 * className: YcMappingResolver
 * version: 1.0
 * description:
 */
@Component
public class YcMappingResolver {

    private static final Logger log = LoggerFactory.getLogger(YcMappingResolver.class);

    @Value("${spring.application.simple-name:ylr}")
    private String applicationSimpleName;

    private final YcMappingClient ycMappingClient;

    public YcMappingResolver(YcMappingClient ycMappingClient) {
        this.ycMappingClient = ycMappingClient;
    }

    /**
     * 获取配置值操作
     * @param key 键
     * @return 结果数据
     */
    public String getStringValue(String key) {
        Result<SimpleMappingDto> result = ycMappingClient.getMapping(key);
        if (result.isFail()) {
            log.warn("{}模块 => 1、获取键值对配置失败。message={}", applicationSimpleName, result.getMsg());
            throw new YlrException(result);
        }
        SimpleMappingDto simpleMappingDto = result.getData();
        return simpleMappingDto.getMapValue();
    }

    /**
     * 获取配置值操作
     * @param key 键
     * @param tClass 泛型class对象
     * @return 结果数据
     * @param <T> 泛型类型
     */
    public <T> T getValue(String key, Class<T> tClass) {
        Result<SimpleMappingDto> result = ycMappingClient.getMapping(key);
        if (result.isFail()) {
            log.warn("{}模块 => 2、获取键值对配置失败。message={}", applicationSimpleName, result.getMsg());
            throw new YlrException(result);
        }
        SimpleMappingDto simpleMappingDto = result.getData();
        String value = simpleMappingDto.getMapValue();
        // 数据解析返回
        return JSON.parseObject(value, tClass);
    }

    /**
     * 获取配置值操作
     * @param key 键
     * @param tClass 泛型class对象
     * @return 结果数据
     * @param <T> 泛型类型
     */
    public <T> List<T> findValue(String key, Class<T> tClass) {
        Result<SimpleMappingDto> result = ycMappingClient.getMapping(key);
        if (result.isFail()) {
            log.warn("{}模块 => 3、获取键值对配置失败。message={}", applicationSimpleName, result.getMsg());
            throw new YlrException(result);
        }
        SimpleMappingDto simpleMappingDto = result.getData();
        String value = simpleMappingDto.getMapValue();
        // 数据解析返回
        return JSON.parseArray(value, tClass);
    }
}
